import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    port: 5173,
    proxy: {
      // 专门为U9库存查询系统设置的代理 - 必须放在通用/api代理之前
      '/api/u9-inventory': {
        target: 'http://172.16.8.223',
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/api\/u9-inventory/, '/U9/RestServices/UFIDA.U9.Cust.YHHT.DomainMainSV.DataQueryReport.IQNanTongWhQoh.svc/do'),
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('🔵 U9代理请求:', proxyReq.method, proxyReq.path);
            // 设置必要的请求头
            proxyReq.setHeader('Content-Type', 'application/json');
            proxyReq.setHeader('Accept', 'application/json');
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('🔵 U9代理响应:', proxyRes.statusCode, req.url);
            // 设置CORS头部
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
            res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
          });
          proxy.on('error', (err, req, res) => {
            console.log('🔵 U9代理错误:', err.message);
          });
        }
      },
      // 代理所有其他 /api 请求到 Python API 服务器
      '/api': {
        target: process.env.VITE_API_BASE_URL || 'http://localhost:8888',
        changeOrigin: true,
        secure: false, // 本地服务器使用http
        // 不重写路径，保持/api前缀
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('🟢 Python API代理错误:', err);
          });
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('🟢 Python API代理 - 发送请求:', req.method, req.url);
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('🟢 Python API代理 - 收到响应:', proxyRes.statusCode, req.url);
          });
        }
      }
    },
    // CORS设置
    cors: {
      origin: true,
      credentials: true
    }
  },
  build: {
    outDir: 'dist',
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks: {
          vue: ['vue', 'vue-router']
        }
      }
    }
  },
  // 环境变量配置
  define: {
    __VUE_OPTIONS_API__: true,
    __VUE_PROD_DEVTOOLS__: false
  }
})
